<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------
namespace Upsanddowns\Controller;
use Think\Controller;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends BaseController {
	// 猜涨跌首页
	public function index() {
        $user_auth= cookie('user_auth');
        $openid= $user_auth['openid'];
        //$openid='wx0a6eff070a1eaf63';
        //获取用户信息
        $user_info=get_table_field($openid,'openid','','follow');
        //获取当前下注活动信息
        $result=M('rose_activity')->where("status=1")->order('periods_start_time desc')->find();
        if($result['is_prized']){
            //活动已结束，跳转到中奖页面
            redirect(U('Index/up_prize'));
        }
        $personsAndOdds = $this->get_beans_and_odds($result['periods']); //获取赔率和人数
        $result['rise_odds']=$personsAndOdds['rise_odds'];//涨赔率
        $result['fall_odds']=$personsAndOdds['fall_odds'];//跌赔率
        $result['rise_num']=$this->get_bet_persons_num($result['periods'],1); //当日买涨人数
        $result['fall_num']=$this->get_bet_persons_num($result['periods'],2); //当日买跌人数
        $result['rise_gold_bean'] = $personsAndOdds['rise_gold_bean'];//涨金豆数
        $result['fall_gold_bean'] = $personsAndOdds['fall_gold_bean'];//跌金豆数

        $current_date = get_now_time();
        //var_dump($current_date);
        $result['bet_date']=date('m-d',strtotime($current_date));//当前竞猜的活动时间
        //获取倒计时
        $countdown=date('Y/m/d H:i:s',mktime(13,00,00,date('m',strtotime($current_date)),date('d',strtotime($current_date)),date('Y',strtotime($current_date))));
        //获取当前正在进行的活动信息 也就是今天
        $tomorrow=strtotime("+1 day");
        $rest=get_time($tomorrow,1,false);
        $startToEnd = '第'.$result['periods'].'期:'.date('m月d日',($result['periods_start_time'])).'-'.date('m月d日',($result['periods_end_time']));
        //获取当前正在进行的活动上证指数
        $stock_info=stock_info('000001');

        //如果今天是活动的最后一天 并且是下午1点以后  就不显示下注信息    //TODO 当前只是让倒计时和下注竞猜时间变为0;
        $day_time=mktime(13,00,00,date('m'),date('d'),date('Y'));

       if(date('Ymd',time())==date('Ymd',$result['periods_end_time']) && time()>$day_time){
            $countdown=0;//获取倒计时
            $result['bet_date']='00-00';//下注竞猜时间
           $this->assign('mark',1);
        }

        $this->assign('user_info',$user_info);
        $this->assign('result',$result);
        $this->assign('stock_info',$stock_info);
        $this->assign('startToEnd',$startToEnd);
        $this->assign('countdown',$countdown);
        //获取赔率曲线图数据
        $odds_data=F('odds');
        $odds['rise_odds']=join(',',$odds_data['rise_odds']);
        $odds['fall_odds']=join(',',$odds_data['fall_odds']);

        $cur_rise_odds=array(
            'name'=>'看涨',
            'value'=>end($odds_data['rise_odds']),
            'xAxis'=>count($odds_data['rise_odds'])-1,
            'yAxis'=>end($odds_data['rise_odds']),
        );
        $cur_fall_odds=array(
            'name'=>'看跌',
            'value'=>end($odds_data['fall_odds']),
            'xAxis'=>count($odds_data['fall_odds'])-1,
            'yAxis'=>end($odds_data['fall_odds']),
        );
        $odds['cur_rise_odds']=json_encode($cur_rise_odds);
        $odds['cur_fall_odds']=json_encode($cur_fall_odds);
        $this->assign('odds',$odds);
        $this->fictitious_data();
        $this->display();
	}

    public function get_beans_and_odds($periods){
        //赔率、金豆数 可以根据rose_buy 表中的数据 进行实时计算
        $info = array();
        $current_date = get_now_time();
        //获取当日赔率
        $where = array();
        $where['profit_gold_bean'] = 0;
        $where['periods'] = $periods;
        $where['date'] = $current_date;
        $buys = M('RoseBuy')->field('type,sum(gold_bean) as current_date_total_bean')->where($where)->group('type')->select();
        foreach($buys as $buy){
            if($buy['type']==1){    //1位涨
                $rise_gold_bean=$buy['current_date_total_bean'];//买涨的总的金豆数
                $info['rise_gold_bean'] = $rise_gold_bean;
            }elseif($buy['type']==2){
                $fall_gold_bean=$buy['current_date_total_bean'];//买跌的总的金豆数
                $info['fall_gold_bean'] = $fall_gold_bean;
            }
        }
        //加上虚拟数据
        $fictitious_data=F('fictitious_data');//虚拟金豆和人数
        $info['rise_gold_bean']=$rise_gold_bean=$rise_gold_bean+$fictitious_data['rise_bean'];//加上虚拟金豆
        $info['fall_gold_bean']=$fall_gold_bean=$fall_gold_bean+$fictitious_data['fall_bean'];
        if(!$rise_gold_bean || !$fall_gold_bean){
            $info['rise_odds'] = 2;
            $info['fall_odds'] = 2;
        }else{
            $info['rise_odds'] = sprintf("%.2f",($rise_gold_bean+$fall_gold_bean)/$rise_gold_bean);
            $info['fall_odds'] = sprintf("%.2f",($rise_gold_bean+$fall_gold_bean)/$fall_gold_bean);
        }
        //限制赔率最大为5
        $info['rise_odds']=$info['rise_odds']>"5.0"?"5.0":$info['rise_odds'];
        $info['fall_odds']=$info['fall_odds']>"5.0"?"5.0":$info['fall_odds'];
        return $info;
    }

    public function get_bet_persons_num($periods,$type=1){
        //赔率、金豆数 可以根据rose_buy 表中的数据 进行实时计算
        $current_date = get_now_time();
        //获取当日赔率
        $where = array();
        $where['profit_gold_bean'] = 0;
        $where['periods'] = $periods;
        $where['type'] = $type;
        $where['date'] = $current_date;
        $persons_num = M('RoseBuy')->where($where)->count('distinct user_id');
        //加上虚拟人数
        $fictitious_data=F('fictitious_data');//虚拟金豆和人数的数据
        $fictitious_persons=$type==1?$fictitious_data['rise_num']:$fictitious_data['fall_num'];//虚拟人数
        return $persons_num+$fictitious_persons;
        //return sprintf("%.2f",$odds);
    }

    /**
     * 用户下注
     */
    public function bet(){
        $user_auth= cookie('user_auth');
        $openid= $user_auth['openid'];
        $result=array('status'=>0,'mes'=>'','data'=>'');
        //$openid='wx0a6eff070a1eaf63';
        //获取用户信息
        $user_info=get_table_field($openid,'openid','','follow');
        //没有关注 不能下注
        if(!$user_info['subscribe']){
            $result['status']=1;
            $result['mes']='请先扫描下方二维码，关注官方公众号！';
            $this->ajaxReturn($result);
        }
        //获取当前活动改为当前进行时期数TODO
        $activity_info=M('rose_activity')->where("status=1")->order('periods_start_time desc')->find();
        $current_date = get_now_time();
        //如果今天是活动的最后一天 并且是下午1点以后  就不能下注
        $day_time=mktime(13,00,00,date('m'),date('d'),date('Y'));
         if((date('Ymd')==date('Ymd',$activity_info['periods_end_time'])) && $current_date==date('Ymd',$activity_info['periods_end_time']) && time()>$day_time){
             $result['status']=1;
             $result['mes']='对不起，下期活动还未开始！';
             $this->ajaxReturn($result);
         }
        $type=I('post.type',1,'intval');
        $gold_bean=I('post.gold_bean',0,'intval');
        //检测用户输入的金豆是否合法
        if($gold_bean<100 || $gold_bean>intval($user_info['gold_bean'])){
            $result['status']=1;
            $result['mes']='你输入的金豆不正确或你的金豆余额不足';
            $this->ajaxReturn($result);
        }
        $data=array(
            'user_id'=>$user_info['id'],
            //'rose_activity_id'=>$activity_info['id'],//这里的改为期数TODO
            'periods'=>$activity_info['periods'],
            'type'=>$type,
            //'time'=>$activity_info['time'],
            'date'=>$current_date
        );
        //当前活动用户是否已买过
        //$res=M('rose_buy')->field('id')->where('type='.$type.' and user_id="'.$user_info['id'].'" and rose_activity_id="'.$activity_info['id'].'"')->find();
        $data['gold_bean']=$gold_bean;
        //$data['odds']=$this->get_odds($activity_info['id'],$type);
        $personsAndOdds = $this->get_beans_and_odds($activity_info['periods']); //获取赔率和人数
        if($type==1){
            $data['odds']=$personsAndOdds['rise_odds'];//涨赔率
        }elseif($type==2){
            $data['odds']=$personsAndOdds['fall_odds'];//跌赔率
        }
        $data['add_time']=time();
        if($rose_buy_id=M('rose_buy')->add($data)){
            $other=array('user_id'=>$user_info['id'],'rose_activity_id'=>$activity_info['id'],'rose_buy_id'=>$rose_buy_id,'type'=>1,'log_info'=>'');
            //减少用户帐户中的金豆并记录日志
            modify_account(array('gold_bean'=>-$gold_bean),$other);
            
            $this->ajaxReturn($result);

        }
    }

    /**
     * 用户分享金豆加1000
     */
    public function share(){
        $result=array('status'=>1,'mes'=>'','data'=>'');
        $user_auth= cookie('user_auth');
        $openid= $user_auth['openid'];
        //$openid='o6VUpxI3SRM2vaw9FJIMUmxjO2to';
        //获取用户信息
        $user_info=get_table_field($openid,'openid','','follow');
        $where['openid']= $openid;
        $where['add_time'] = array(array('elt',mktime(23,59,59,date('m'),date('d'),date('Y'))),array('gt',mktime(00,00,00,date('m'),date('d'),date('Y'))),'and');
        $where['gold_bean'] = array('neq',0);
        $where['type']=1;
        //查找用户当天分享获得金豆的次数
        $num=M('weixin_share')->where($where)->count();
        //获取最新分享获得金豆的数据
        $new_share_time=M('weixin_share')->where($where)->order('add_time desc')->getField("add_time");
        $res=M('weixin_share')->add(array('openid'=>$openid,'type'=>1,'add_time'=>time()));
        if($num<3 && $res && (time()-$new_share_time)>3600 && $user_info['subscribe']){
            $other=array('user_id'=>$user_info['id'],'type'=>3,'log_info'=>'每天分享送1000金豆');
            //减少用户帐户中的金豆并记录日志
            modify_account(array('gold_bean'=>1000),$other);
            $num++;
            $result=array('status'=>0,'mes'=>'第'.$num.'次分享，送1000金豆','data'=>'');
            $data['gold_bean']=1000;
            M('weixin_share')-> where('id='.$res)->setField($data);
       }
        $this->ajaxReturn($result);
    }
	/*
	 *获取上期中奖名单
	 */
	public function up_prize(){
		//获取当前期并判断是否有正在进行的期数
		$periods = M('RoseActivity')->where('status=1')->order('periods desc')->getField('periods');//
		//获取上期期数
		if($periods){//如果存在进行期数
			if(get_table_field($periods,'periods','is_prized','rose_activity')){
				$pre_periods=$periods;
			}else{
				$pre_where['periods']=array('neq',$periods);
				$pre_periods=M('RoseActivity')->where($pre_where)->order('periods desc')->getField('periods');
			}
		}else{//如果不存在进行期数
			$pre_periods = M('RoseActivity')->order('periods desc')->getField('periods');//	
		}
		//根据期数获取中奖奖
		$prize['periods']=$pre_periods;
		$prize_list=M('rose_prize')->where($prize)->order('prize_money desc')->select();
		//var_dump($prize_list);
		//合并
		foreach($prize_list as $k=>$v){
			$where_log= array();
			$where_log['rose_prize_id']=$v['id'];
        	$where_log['periods'] = $pre_periods;
			$winlog_list=M('win_log')->field('user_id,rose_prize_id')->where($where_log)->select();
			$count=count($winlog_list);
			if($count>0){
				$prize_list[$k]['nickname'].="<tr>";	
				foreach($winlog_list as $key=>$val){
					if($val['user_id']){
						$prize_list[$k]['user_id'][]=$val['user_id'];
						$where['id']=array('eq',$val['user_id']);
						$nickname = M('follow')->where($where)->getField('nickname');
						if($key%2==0 && $nickname!=''){
							if($key==($count-1)){
								$prize_list[$k]['nickname'].="<td class='set_width_left'>".$nickname.'</td></tr>';
							}else{
								$prize_list[$k]['nickname'].="<td class='set_width_left'>".$nickname.'</td>';
							}
						}elseif($key%2!=0){
							if($key==($count-1)){
								$prize_list[$k]['nickname'].="<td class='set_width_right'>".$nickname.'</td></tr>';
							}else{
								$prize_list[$k]['nickname'].="<td class='set_width_right'>".$nickname.'</td></tr></tr>';
							}
							
						}
					}
				}
			}
			else{
				$prize_list[$k]['nickname']="<tr><td class='no_winning' cols='2'>还未有用户中奖</td></tr>";		
			}
		}
		//echo '<meta charset="utf-8">';
		//var_dump($prize_list);
		$this->assign('pre_periods',$pre_periods);
		$this->assign('prize_list',$prize_list);
		$this->display();	
	}

	/*
	 *获取中奖奖项
	 */
	private function periods_prize($pre_periods){
		$prize['periods']=$pre_periods;
		$list=M('rose_prize')->where($prize)->order('prize_money desc')->select();
		return $list;
	}


    /**
     * 缓存虚拟金豆和人数
     */
    public function fictitious_data(){

        $data=F('fictitious_data');
        $time=mktime(13,00,00,date('m'),date('d'),date('Y'));
        $prev_time=$data['time']?$data['time']:0;
        $rest=is_rest(date('Ymd'));
        //获取当前下注活动信息
        $result=M('rose_activity')->where("status=1")->order('periods_start_time desc')->find();
        //重新生成虚拟金豆和人数
        //当前时间大于1点 and 上次缓存的时间不是今天  and 今天不是节假日  或者 今天是节假日and今天是当前活动的开始时间
        if(time()>=$time && $prev_time!=date('Ymd') && get_now_time()!=date('Ymd',$result['periods_end_time']) && !$rest[date('Ymd')] || (date('Ymd')==date('Ymd',$result['periods_start_time']) && $rest[date('Ymd')])){
            F('fictitious_data',null);
            $data=array(
                'rise_bean'=>rand(14000,16000),
                'fall_bean'=>rand(14000,16000),
                'rise_num'=>rand(2,7),
                'fall_num'=>rand(2,7),
                'time'=>date('Ymd')
            );
            F('fictitious_data',$data);
       }

    }

}



